package mvc;

import java.util.ArrayList;
import java.util.List;

public class TicTacToeDefaulModel implements TicTacToeModel {

	private int board[][] = new int[3][3];
	
	private boolean gameOver = false;
	
	private int winner = TicTacToeModel.PLAYER_NONE;
	
	private List<TicTacToeListener> listeners = new ArrayList<TicTacToeListener>();
	
	@Override
	public int getPiece(int row, int col) {
		return board[row][col];
	}

	@Override
	public void setPiece(int row, int col, int player) {

		if(board[row][col]!=player){
			board[row][col]=player;
			for (TicTacToeListener listener : listeners) {
				listener.pieceWasSet(new TicTacToeEvent(row, col, player));
			}
			
			updateGameStatus();
		}
		
		
	}

	private void updateGameStatus() {
		if(computeWinner()!=0){
			winner = computeWinner();
			setGameOver(true);
		}
		
	}

	@Override
	public boolean isGameOver() {
		return gameOver;
	}

	@Override
	public int getGewinner() {
		return winner;
	}

	@Override
	public void restart() {
		if(!gameOver)
			setGameOver(true);
		
		for (int row = 0; row < board.length; row++) {
			for (int col = 0; col < board[0].length; col++) {
				board[row][col] = TicTacToeModel.PLAYER_NONE;
			}
		}
		
		winner = TicTacToeModel.PLAYER_NONE;
		setGameOver(false);

	}

	@Override
	public void addTicTacToeListener(TicTacToeListener listener) {
		listeners.add(listener);

	}

	@Override
	public void removeTicTacToeListener(TicTacToeListener listener) {
		listeners.remove(listener);
	}

	public void setGameOver(boolean gameOver) {
		if(this.gameOver != gameOver){
			this.gameOver = gameOver;
		
			for (TicTacToeListener listener : listeners) {
				listener.statusChanged(new TicTacToeEvent(gameOver));
				
			}
		}
	}
	
	public int computeWinner()
	{
		for (int i = 0; i < board.length; i++) {
			if(getPiece(i, 0) != TicTacToeModel.PLAYER_NONE && equal(i,0,i,1,i,2))
				return getPiece(i, 0);
			if(getPiece(0, i) != TicTacToeModel.PLAYER_NONE && equal(0, i, 1, i, 2, i))
				return getPiece(0, i);
			
		}
		if(getPiece(0, 0) != TicTacToeModel.PLAYER_NONE && equal(0,0,1,1,2,2))
			return getPiece(0, 0);
		if(getPiece(0, 2) != TicTacToeModel.PLAYER_NONE && equal(0, 2, 1, 1, 2, 0))
			return getPiece(0, 2);
		return TicTacToeModel.PLAYER_NONE;
		
	}
	
	public boolean equal(int r0, int c0, int r1, int c1, int r2, int c2){
		return (getPiece(r0, c0) == getPiece(r1, c1) && getPiece(r1, c1) == getPiece(r2, c2));
	}
	
	public boolean existsFreeFields(){
		
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				if(board[i][j]==TicTacToeModel.PLAYER_NONE) return true;
			}
		}
		
		return false;
	}

}
